package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.DimensionApi;
import com.tanhua.model.mongo.Dimension;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 维度接口实现类
 */
@DubboService
public class DimensionApiImpl implements DimensionApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 保存维度
     *
     * @param dimensions
     */
    @Override
    public void save(List<Dimension> dimensions) {
        ObjectId reportId = dimensions.get(0).getReportId();
        Query query = new Query(Criteria.where("reportId").is(reportId));
        if (mongoTemplate.exists(query, Dimension.class)) {
            mongoTemplate.remove(query, Dimension.class);
        }
        for (Dimension dimension : dimensions) {
            mongoTemplate.insert(dimension);
        }

    }

    /**
     * 根据报表id获取维度
     *
     * @param reportId
     */
    @Override
    public List<Dimension> getByReportId(ObjectId reportId) {
        Query query = new Query(Criteria.where("reportId").is(reportId));
        return mongoTemplate.find(query, Dimension.class);
    }
}
